<template>
  <div class="main-container">
    <layout class="a05">
      <template slot="search">
        <el-form inline :model="formSearch">
          <div class="search-left">
            <el-form-item label="订货单位：" label-width="100px">
              <el-input v-model="formSearch.orderUnit" class="w150" placeholder="输入订货单位" clearable></el-input>
            </el-form-item>
            <el-form-item label="产品工号：" label-width="100px">
              <el-input v-model="formSearch.workingNumber" class="w150" placeholder="输入产品工号" clearable></el-input>
            </el-form-item>
            <el-form-item label="通知单号：" label-width="100px">
              <el-input v-model="formSearch.noticeNumber" class="w150" placeholder="输入通知单号" clearable></el-input>
            </el-form-item>
            <br />
            <el-form-item label="图纸号：" label-width="100px">
              <el-input v-model="formSearch.drawingNumber" class="w150" placeholder="输入图纸号" clearable></el-input>
            </el-form-item>
            <el-form-item label="产品名称：" label-width="100px">
              <el-input v-model="formSearch.productName" class="w150" placeholder="输入产品名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="填单日期：" label-width="100px">
              <el-date-picker v-model="formSearch.beginTime" type="date" placeholder="开始日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-date-picker v-model="formSearch.endTime" type="date" placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </div>
          <div class="search-right">
            <el-button size="small" @click="clearNoticeSearch">清 空</el-button>
            <el-button size="small" type="primary" icon="el-icon-search" @click="onSearchNotice()">查 询</el-button>
          </div>
        </el-form>
      </template>
      <template slot="operation">
        <div class="operation-left">
          <!-- 通知单状态数量区域 -->
          <div class="total" v-for="(item, index) in totalLabel" :key="index">
            <div class="total_title" :style="{ backgroundColor: item.color }">{{ item.name }}</div>
            <el-button size="small" class="total_btn" :class="curState == item.name ? 'bg-red' : ''"
              @click="onChangeNoticeState(item)">{{ totalStates[item.type] }}</el-button>
          </div>
          <!-- 通知单操作按钮区域 -->
          <div class="operationBtn">
            <el-button id="btnB1CreateNotice" size="small" type="primary" @click="addNotice()"
              v-if="$checkAuth('新建销售产品通知单')">新增通知单</el-button>
            <el-button size="small" type="primary" @click="searchProductList()">产品列表查询</el-button>
            <el-button size="small" type="primary" @click="resetNoticeSerialNumber()">重置流水号</el-button>

          </div>
          <!-- 新增通知单弹框 -->
          <dialog-add ref="dialogAdd" @update="getSearchNoticeList()"></dialog-add>
        </div>
      </template>
      <template slot="content">
        <el-table border stripe height="600" :data="noticeList" row-key="noticeId" @row-dblclick="rowDoubleClick">
          <el-table-column type="index" label="序号" align="center" width="60" fixed></el-table-column>
          <el-table-column prop="createTime" label="填单日期" align="center" min-width="120"></el-table-column>
          <el-table-column prop="noticeNumber" label="通知单号" align="center" min-width="100"></el-table-column>
          <el-table-column prop="orderUnit" label="订货单位" align="center" min-width="120"></el-table-column>
          <el-table-column prop="deliveryPlace" label="交货地点" align="center" min-width="100"></el-table-column>
          <el-table-column prop="deliveryState" label="交货状态" align="center" min-width="100"></el-table-column>
          <el-table-column prop="deliveryMethod" label="运输方式" align="center" min-width="100"></el-table-column>
          <el-table-column prop="deliveryDate" label="交货日期" align="center" min-width="120"></el-table-column>
          <el-table-column prop="state" label="通知单状态" align="center" min-width="120"></el-table-column>
          <el-table-column prop="state" label="操作" align="center" fixed="right" width="110">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" :id="'btnB1Detail' + scope.row.noticeNumber"
                @click="rowDoubleClick(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="visibility" label="是否可见" align="center" fixed="right" width="100"
            v-if="$checkAuth('管理员可见')">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.visibility" @change="changeVisibility(scope.row)" active-color="#13ce66"
                inactive-color="#999"> </el-switch>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination @size-change="handleNoticeSizeChange" @current-change="handleNoticeCurrentChange"
          :current-page="formSearch.page" :page-sizes="[10, 20, 30, 40]" :page-size="formSearch.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="totalNotice" background class="mt10">
        </el-pagination>
      </template>
    </layout>
    <!-- </el-tab-pane>
  </el-tabs> -->
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import { State, namespace, Action, Mutation } from 'vuex-class'
import Layout from '@/views/_common/Layout.vue'
import dialogAdd from './Dialog.vue'
import detail from './detail.vue'

import { getNoticeList, commitNotice, commitvisible, getTotal, deleteNotice, exportNotice, resetNoticeSerialNumber } from '@/api/notice'
import { Notification } from 'element-ui'
import _ from 'lodash'
import dayjs from 'dayjs'

const vuexNotice = namespace('NewNotice')
const vuexLogin = namespace('Login')

@Component({
  /*
      这里写自定义指令、过滤器、守卫钩子函数
  */
  components: {
    Layout,
    dialogAdd,
    detail,
  }
})
export default class Index extends Vue {
  public $refs!: {
    dialogAdd: any
    detail: any
  }

  @vuexNotice.Action DETELE_NOTICE: any
  @vuexNotice.Action CANCEL_CHANGE: any

  // data -- start
  // 通知单下单
  formSearch: any = {
    beginTime: '', //查询开始日期
    endTime: '', //查询结束日期
    orderUnit: '', //订货单位
    workingNumber: '', //产品工号
    noticeNumber: '', //通知单号
    drawingNumber: '', //产品图号
    productName: '', //产品名称
    state: '',
    page: 1,
    pageSize: 10,
    visibility: false
  }
  // 可修改状态
  modifyState: any[] = ['未提交', '审核未通过', '变更未提交', '变更审核未通过']
  // 可删除状态
  deleteState: any[] = ['未提交', '审核未通过']
  // 可提交状态
  commitState: any[] = ['未提交', '审核未通过', '变更未提交', '变更审核未通过']
  // 可审核状态
  reviewState: any[] = ['待审核', '变更待审核', '批准未通过', '变更批准未通过']
  // 可批准状态
  allowState: any[] = ['待批准', '变更待批准']
  @vuexLogin.State isAdmin: any
  noticeList: any[] = []
  totalNotice: any = 0
  totalStates: any = {}

  // 审核、批准、按钮的显示
  showReview: any
  showApproval: any
  showBtn: any
  showDao: any

  stateList: any[] = [
    // 工装产品的状态
    '工艺设计',
    '工艺审批',
    '待派工',
    '生产中',
    '已完成',
    '工艺变更设计',
    '工艺变更审批'
  ]
  totalLabel: any[] = [
    { name: '工单总数', color: '#666666', type: 'allTotal' },
    { name: '未提交', color: '#ff0000', type: 'submitTotal' },
    { name: '待初审', color: '#ff0099', type: 'preauditTotal' },
    { name: '待审核', color: '#ff9900', type: 'auditTotal' },
    { name: '待批准', color: '#ffcc00', type: 'approveTotal' },
    { name: '进行中', color: '#3399cc', type: 'inTotal' },
    { name: '已完成', color: '#33cc66', type: 'endTotal' }
  ]
  curState: string = '工单总数'
  curTabName: string = 'first'
  async getSearchNoticeList() {
    let formSearch = _.cloneDeep(this.formSearch)
    let res1 = await getNoticeList(formSearch)
    this.totalNotice = _.get(res1, 'total', 0)
    this.noticeList = _.get(res1, 'data', [])
    let res2 = await getTotal(formSearch)
    this.totalStates = _.get(res2, 'data', [])
  }
  onSearchNotice() {
    if (this.formSearch.beginTime) {
      if (this.formSearch.endTime) {
        this.compareSearchDate()
      } else {
        this.$alert('请同时输入搜索开始与结束日期后，进行搜索', '操作提示', {
          confirmButtonText: '确定',
          type: 'warning'
        })
      }
    } else if (this.formSearch.endTime) {
      if (this.formSearch.beginTime) {
        this.compareSearchDate()
      } else {
        this.$alert('请同时输入搜索开始与结束日期后，进行搜索', '操作提示', {
          confirmButtonText: '确定',
          type: 'warning'
        })
      }
    } else {
      this.formSearch.page = 1
      this.getSearchNoticeList()
    }
  }
  compareSearchDate() {
    this.formSearch.endTime = dayjs(this.formSearch.endTime).format('YYYY-MM-DD')
    this.formSearch.beginTime = dayjs(this.formSearch.beginTime).format('YYYY-MM-DD')
    if (this.formSearch.endTime > this.formSearch.beginTime) {
      this.getSearchNoticeList()
    } else {
      this.$alert('请输入搜索结束日期大于开始日期', '操作提示', {
        confirmButtonText: '确定',
        type: 'warning'
      })
    }
  }
  onChangeNoticeState(data) {
    this.curState = this.formSearch.state = data['name']
    this.formSearch.page = 1
    this.getSearchNoticeList()
  }
  clearNoticeSearch() {
    this.formSearch.orderUnit = ''
    this.formSearch.workingNumber = ''
    this.formSearch.noticeNumber = ''
    this.formSearch.drawingNumber = ''
    this.formSearch.productName = ''
    this.formSearch.beginTime = ''
    this.formSearch.endTime = ''
    this.formSearch.state = ''
    this.curState = '工单总数'
    this.getSearchNoticeList()
  }
  handleNoticeSizeChange(newSize) {
    // 分页功能
    this.formSearch.pageSize = newSize
    this.getSearchNoticeList()
  }
  handleNoticeCurrentChange(newPage) {
    this.formSearch.page = newPage
    this.getSearchNoticeList()
  }
  // 新增通知单
  addNotice() {
    this.$refs.dialogAdd.open()
  }
  // 产品列表查询 页面跳转
  searchProductList() {
    this.$router.push({ name: 'noticeProductList' })
  }
  /* 点击提交 审核 批准按钮
   * @param type 提交 1 审核 2 批准 3
   */
  onHandleNotice(notice, type: Number) {
    const handleData = {
      noticeId: '',
      handleName: '',
      handleConclusion: true,
      handleRemark: ''
    }
    switch (type) {
      case 1:
        handleData.noticeId = notice.noticeId
        handleData.handleName = '提交'
        handleData.handleConclusion = true

        this.$prompt('请输入操作备注', `提交通知单-产品工号${notice.workingNumber}`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then((value: any) => {
            console.log('点击了确定')
            console.log(value)
            handleData.handleRemark = value.value
            this.submitNotice(handleData)
          })
          .catch(() => {
            console.log('点击了取消')
            this.$message({
              type: 'info',
              message: '取消提交'
            })
          })

        break
      case 2:
        // this.$refs.dialogReview.bindNoticeInfo(notice)
        // this.$refs.dialogReview.open(notice.noticeId, '审核')
        this.$router.push({ name: 'detail', params: { typeNumber: '3', row: notice, showApproval: 'false', showReview: 'true', showBtn: 'false', showDao: 'true' } })
        break
      case 3:
        this.$router.push({ name: 'detail', params: { typeNumber: '3', row: notice, showApproval: 'true', showReview: 'false', showBtn: 'false', showDao: 'true' } })
        break
    }
  }
  async submitNotice(handleData: any) {
    let res = await commitNotice(handleData)
    if (res.code == 200) {
      this.$message({
        type: 'success',
        message: '提交成功'
      })
      this.getSearchNoticeList()
    }
  }
  /**
   * 点击修改按钮，获取通知单详情数据，跳转修改组件
   */
  editNotice(noticeData) {
    //传基础数据
    let canEditState = ['未提交', '审核未通过', '变更未提交', '变更审核未通过', '进行中']
    if (canEditState.includes(noticeData.state)) {
      this.$router.push({ name: 'detail', params: { typeNumber: '4', row: noticeData, showApproval: 'false', showReview: 'false', showBtn: 'true', showDao: 'true' } })
    } else {
      this.$message.warning('此状态下通知单不可修改！')
    }
  }
  /**
   * 点击删除按钮，删除通知单
   */
  delNotice(noticeData) {
    this.$alert(`您确定删除通知单[${noticeData.noticeNumber}]？`, '操作提示', {
      confirmButtonText: '确定',
      type: 'error',
      callback: action => {
        if (action === 'confirm') {
          this.$confirm('此操作将永久删除该数据, 是否继续?', '操作提示', {
            cancelButtonText: '取消',
            confirmButtonText: '确定',
            type: 'warning'
          })
            .then(async () => {
              //向后端传递删除数据id
              let resp = await deleteNotice({ noticeId: noticeData.noticeId }).catch((err: any) => {
                Notification.error(err)
              })
              if (resp) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this.getSearchNoticeList()
              }
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              })
            })
        }
      }
    })
  }
  /**
   * 点击导出按钮，导出通知单文档
   */
  async exportNotice(noticeData) {
    window.open('/notice/export?noticeId=' + noticeData.noticeId)
  }

  async changeVisibility(row) {
    const { noticeId, visibility } = row
    const params = {
      noticeId: noticeId,
      visibility: visibility
    }
    let res = await commitvisible(params).catch((err: any) => {
      Notification.error(err)
    })
    if (!res) {
      row.visibility = !row.visibility
    } else {
      this.$message({
        type: 'success',
        message: '设置成功'
      })
    }
  }
  async rowDoubleClick(row) {
    this.$router.push({ name: 'detail', params: { typeNumber: '1', row, showApproval: 'false', showReview: 'false', showBtn: 'true', showDao: 'true' } })
  }
  async resetNoticeSerialNumber() {
    let noticeSerialNumber = Number(window.prompt("输入当前使用流水号，如没有则输入0", "0"))
    let res = await resetNoticeSerialNumber({ noticeSerialNumber: noticeSerialNumber })
    if (res.code == 200) {
      this.$message({
        type: 'success',
        message: '重置成功，下一个流水号以' + (noticeSerialNumber + 1) + '开始'
      })
    }

  }


  /**
   * 取消变更
   */
  // cancel() {
  //   this.CANCEL_CHANGE({ noticeId: this.selectedNoticeId })
  //   this.GET_NOTICE(this.formSearch)
  // }

  // 钩子函数 --- start
  mounted() {
    // 之所以要推迟该接口的请求，是因为担心上一个seek接口获取isAdmin数据执行太慢
    // 异步都有这个毛病，我希望该接口能在seek接口执行完并赋值之后再执行,,,换句话就是希望这里同步
    setTimeout(() => {
      this.formSearch.visibility = !this.isAdmin
      this.getSearchNoticeList()
    }, 500)
  }
  // 钩子函数 --- end

  created() { }
}
</script>

<style lang="scss" scoped>
.a05 {
  .total {
    float: left;
    border: 1px solid #ccc;
    margin-right: 10px;

    .total_title {
      width: 100px;
      color: #fff;
      height: 30px;
      line-height: 30px;
      text-align: center;
      border: 1px solid #ccc;
      border-top: none;
      border-left: none;
      border-right: none;
    }

    .total_btn {
      height: 50px;
      width: 100px;
      border-radius: 0;
      border: none;
      font-size: 28px;

      &:hover {
        color: #000;
        background: #fff;
      }

      &:focus {
        background: #ff0000;
        color: #fff;
      }
    }
  }

  .data {
    width: 70%;
    height: 30px;
    line-height: 30px;

    .el-icon-circle-close {
      line-height: 22px;
    }
  }

  .el-date-editor .el-range__icon {
    line-height: 25px;
  }

  .el-date-editor .el-range-separator {
    line-height: 23px;
  }
}

// .layout .content .list > div {
//   height: auto;
// }
.el-tabs {
  // min-width: 1260px;/* 1200 + 20*2(padding) */
  // min-height: calc(100vh - 140px);
  padding: 0 20px;
  margin: 0px 10px 0;
  border: 1px solid #e4e7ed;
  background-color: #fff;

  // .el-tab-pane {
  //   min-width: 1200px!important;
  // }
  .el-tabs__content {
    min-width: 1200px;
  }
}

.operationBtn {
  float: left;
  margin-right: 10px;
  margin-top: 45px;
}
</style>
